<?php

class My_Controller_Plugin_Locale extends Zend_Controller_Plugin_Abstract
{
    
    private $_locale;
    private $_translate;
    
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $moduleName = $request->getModuleName();
        
        $config = Zend_Registry::get('config');
        
        $session = Zend_Registry::get('session');
        
        $cache = Zend_Registry::get('cache');
        
        Zend_Locale::setCache($cache);
        Zend_Translate::setCache($cache);
        
        Zend_Locale::$compatibilityMode = false;
        
        $this->_locale = new Zend_Locale();
        
        //Application wide locale
        Zend_Registry::set('Zend_Locale', $this->_locale);

        $translate = new Zend_Translate('gettext', 
                                        APPLICATION_PATH . '/modules/' . $moduleName . '/locales', 
        								null,
                                        array('scan' => Zend_Translate::LOCALE_DIRECTORY));
                                        
        Zend_Registry::set('Zend_Translate', $translate);
        $this->_translate = $translate;
        
        if (null !== $request->getParam('locale')) {
            $this->setLocale($request->getParam('locale'));
        }
        else if ($session->locale) {
            $this->setLocale($session->locale);
        }
        else {
            $this->setLocale($config->locale->default);
        }
            
        Zend_Locale_Format::setOptions(array('locale' => $this->_locale)); 
    }

    public function setLocale($newLocale)
    {
        $logger = Zend_Registry::get('logger');
        $session = Zend_Registry::get('session');
        
        if ($this->_locale->isLocale($newLocale, true)) {
            $locale = $newLocale;
            $this->_locale->setLocale($locale);
            
            if (!$this->_translate->isAvailable($this->_locale->getLanguage()))
                $language = Zend_Registry::get('config')->locale->default;
            else
                $language = $this->_locale->toString();
            
            $this->_translate->setLocale($language);
            
            $session->locale = $this->_locale->toString();
                
            $logger->info("Zend_Locale set to '" . $locale . "'.");
            $logger->info("Zend_Translate set to '" . $language . "'.");
            
            return true;
        }
        
        $logger->info("Invalid locale '" . $newLocale . "'.");
        return false;
    }

}